package com.matto1990.app.madlab.ui;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import net.londatiga.android.quickaction.ActionItem;
import net.londatiga.android.quickaction.QuickAction;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.matto1990.app.madlab.R;
import com.matto1990.app.madlab.provider.MadlabContract.Events;
import com.matto1990.app.madlab.provider.MadlabContract.Meetups;
import com.matto1990.app.madlab.util.NotifyingAsyncQueryHandler;
import com.matto1990.app.madlab.util.TitlebarActivity;
import com.matto1990.app.madlab.util.NotifyingAsyncQueryHandler.AsyncQueryListener;

public class CalendarActivity extends TitlebarActivity implements AsyncQueryListener {
    public static final String TAG = "Madlab";
    
    private Context context;
    private ListView list;
    private CursorAdapter adapter;
    private NotifyingAsyncQueryHandler handler;
    private Uri meetupsUri;

    private ActionItem allMeetups;
    private ActionItem futureMeetups;
    private ActionItem pastMeetups;
    private Button quickactionsButton;
    private QuickAction quickactionsMenu;
    private TextView meetupsActivityTitle;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Set the layout
        setContentView(R.layout.activity_meetups);
        
        // Setup the title bar UI
        setupTitlebar();
        
        // Get the application context and content url
        context = getApplicationContext();
        meetupsUri = Meetups.CONTENT_URI;
        
        // Setup the action list for the quickactions menu
        allMeetups = new ActionItem();
        allMeetups.setTitle("All");
        allMeetups.setOnClickListener(allMeetupsButtonListener);
        
        futureMeetups = new ActionItem();
        futureMeetups.setTitle("Upcoming");
        futureMeetups.setOnClickListener(futureMeetupsButtonListener);
        
        pastMeetups = new ActionItem();
        pastMeetups.setTitle("Past");
        pastMeetups.setOnClickListener(pastMeetupsButtonListener);
        
        // Setup the quickactions button
        quickactionsButton = (Button) this.findViewById(R.id.btn_quickaction_events);
        quickactionsButton.setOnClickListener(quickactionsButtonListener);
        
        // Get the title view
        meetupsActivityTitle = (TextView) findViewById(R.id.activity_meetups_title);
        
        // Get the list and set its adapter
        list = (ListView) findViewById(R.id.meetups_list);
        adapter = new MeetupsAdapter(context);
        list.setOnItemClickListener(itemClickListener);
        list.setAdapter(adapter);
        
        // Start background query to load meetups
        handler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
        futureMeetupsQuery();
        
        // Setup the title bar UI
        //TitlebarSetup.setup(this);
    }
    
    // Sets the query as all meetups
    private void allMeetupsQuery() {
        meetupsActivityTitle.setText("All Meetups");
        handler.startQuery(meetupsUri, MeetupsQuery.PROJECTION, Meetups.DEFAULT_SORT);
    }
    
    // Sets the query to be just future events
    private void futureMeetupsQuery() {
        meetupsActivityTitle.setText("Upcoming Meetups");
        handler.startQuery(meetupsUri, MeetupsQuery.PROJECTION, Meetups.MEETUP_START_DATETIME + ">=date('now','start of day')", null, Meetups.DEFAULT_SORT);
    }
    
    // Sets the query to be just past events
    private void pastMeetupsQuery() {
        meetupsActivityTitle.setText("Past Meetups");
        handler.startQuery(meetupsUri, MeetupsQuery.PROJECTION, Meetups.MEETUP_START_DATETIME + "<date('now','start of day')", null, Meetups.DEFAULT_SORT);
    }
    
    // Run when the query on the content uri is returned
    /** {@inheritDoc} */
    @Override
    public void onQueryComplete(int token, Object cookie, Cursor cursor) {
        // Start managing the cursor and set our adapter to use it
        startManagingCursor(cursor);
        adapter.changeCursor(cursor);
    }
    
    // Shows the quickactions menu
    private OnClickListener quickactionsButtonListener = new View.OnClickListener() {
        public void onClick(View view) {
            quickactionsMenu = new QuickAction(view);
            quickactionsMenu.addActionItem(allMeetups);
            quickactionsMenu.addActionItem(futureMeetups);
            quickactionsMenu.addActionItem(pastMeetups);
            quickactionsMenu.setAnimStyle(QuickAction.ANIM_AUTO);
            quickactionsMenu.show();
        }
    };
    
    // Changes the query to be all meetups
    private OnClickListener allMeetupsButtonListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            allMeetupsQuery();
            quickactionsMenu.dismiss();
        }
    };
    
    // Changes the query to be upcoming meetups
    private OnClickListener futureMeetupsButtonListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            futureMeetupsQuery();
            quickactionsMenu.dismiss();
        }
    };
    
    // Changes the query to be past meetups
    private OnClickListener pastMeetupsButtonListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            pastMeetupsQuery();
            quickactionsMenu.dismiss();
        }
    };
    
    // A click listener for the items in the calendar list
    private OnItemClickListener itemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Get the item from the cursor in this position
            final Cursor cursor = (Cursor) adapter.getItem(position);
            // Get the event id
            final String meetupId = cursor.getString(cursor.getColumnIndex(Meetups.MEETUP_ID));
            // Build a url for that specific event
            final Uri meetupUri = Meetups.buildMeetupUri(meetupId);
            // Make an intent to launch that uri
            final Intent intent = new Intent(Intent.ACTION_VIEW, meetupUri);
            // Send the state
            intent.putExtra(STATE, state);
            // Start the activity
            startActivity(intent);
        }
    };
    
    // Meetups adapter uses a cursor to display the data from the content uri
    private class MeetupsAdapter extends CursorAdapter {
        public MeetupsAdapter(Context context) {
            super(context, null);
        }

        /** {@inheritDoc} */
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            return getLayoutInflater().inflate(R.layout.list_item_meetup_detail, parent, false);
        }

        /** {@inheritDoc} */
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            // Setup some date formats
            final SimpleDateFormat sqlDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            final SimpleDateFormat niceDateFormat = new SimpleDateFormat("d MMMM yyyy 'at' HH:mm");
            
            // Get the views
            final TextView titleView = (TextView) view.findViewById(R.id.event_title);
            final TextView startDateView = (TextView) view.findViewById(R.id.meetup_start_date);
            
            try {
                // Setup the nice date text
                String startDate = cursor.getString(cursor.getColumnIndex(Meetups.MEETUP_START_DATETIME));
                startDate = niceDateFormat.format(sqlDateFormat.parse(startDate));
                
                // Set the view contents
                startDateView.setText(startDate);
                titleView.setText(cursor.getString(cursor.getColumnIndex(Events.EVENT_TITLE)));
            } catch (ParseException e) {
                Log.w(TAG, "Incorrect date format", e);
            }
        }
    }
    
    /** {@link Events} query parameters. */
    private interface MeetupsQuery {
        String[] PROJECTION = {
                "meetups." + BaseColumns._ID,
                Meetups.MEETUP_ID,
                Meetups.MEETUP_TITLE,
                Meetups.MEETUP_START_DATETIME,
                Events.EVENT_TITLE,
                Events.EVENT_INTERESTED
        };
    }
}
